package com.qiteng.apiclientsdk.client;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;

import java.util.HashMap;
import java.util.Map;

import static com.qiteng.apiclientsdk.utils.SignUtils.generateSign;


/**
 * @author qiteng
 */
public class ApiClient {

    private String accessKey;
    private String secretKey;
    private static final String  GATEWAY_ADDRESS = "http://localhost:8090";

    public ApiClient() {
    }

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

/*    public String getNameByGet(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result= HttpUtil.get(GATEWAY_ADDRESS + "/api/name/", paramMap);
        return result;
    }

    public String getNameByPost(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result= HttpUtil.post(GATEWAY_ADDRESS + "/api/name/", paramMap);
        return result;
    }*/

    public String invokeInterface(String params, String path) {
        String result = HttpRequest.post(GATEWAY_ADDRESS + path)
                .body(params)
                .addHeaders(getHeaderMap(params))
                .execute().body();
        return result;
    }

    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> headers = new HashMap<>();
        headers.put("accessKey", accessKey);
        headers.put("body", body);
        headers.put("nonce", RandomUtil.randomNumbers(4));
        headers.put("timestamp", String.valueOf(System.currentTimeMillis()));
        headers.put("sign", generateSign(body, secretKey));
        return headers;
    }
}
